<?php
namespace App\Services;

use App\Wiki;
use App\User;
use App\WikiRevision;
use App\Category;
use Spatie\Activitylog\Models\Activity;
class  WikiActivityLogService {
    // 创建词条
    public function created(Wiki $wiki, User $user)
    {

        activity('wiki.created')
            ->performedOn($wiki)
            ->causedBy($user)
            ->withProperty('title', $wiki->title)
            ->log('创建词条');
    }

    // 添加 / 移除分类
    public function changeCategories(Wiki $wiki, User $user, $oldCategories = [], $newCategories = [])
    {
        if (count($oldCategories) < count($newCategories)) {
            $type = '添加';
            $diff = array_diff($newCategories, $oldCategories);
        } else if(count($oldCategories) > count($newCategories)) {
            $type = '移除';
            $diff = array_diff($oldCategories, $newCategories);
        } else {
            $type = '修改';
            $diff = array_diff($oldCategories, $newCategories);
        }
        if ($diff) {
            $categories = $this->getCategoryById($diff);
            activity('wiki.categories.change')
                ->performedOn($wiki)
                ->causedBy($user)
                ->withProperty('categories', $categories)
                ->log($type .'了话题');
        }

    }
    // 添加版本

    public function createdRevision(Wiki $wiki, WikiRevision $revision)
    {
        activity('wiki.revision.created')
            ->performedOn($wiki)
            ->causedBy($revision->user_id)
            ->withProperty('revision', $revision)
            ->log('添加了版本');
    }

    public function getLogs(Wiki $wiki)
    {
        return $wiki_logs = Activity::with(['causer', 'subject'])->where('subject_id', $wiki->id)
            ->where('subject_type', 'App\Wiki')
            ->where('log_name', '<>', 'commented.wiki')
            ->latest()->limit(10)->get();
    }
    protected function getCategoryById($diff = [])
    {
        return Category::whereIn('id', $diff)->select('id','slug','title')->get()->toArray();
    }
}
